package org.support.small.mallms.config;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.support.small.mallms.contants.AuthConsts;
import org.support.small.mallms.exception.TokenForbiddenException;
import org.support.small.mallms.service.AdminsService;
import org.support.small.mallms.utils.RequestContextUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Objects;

@Component
public class AdminLoginInterceptor implements AsyncHandlerInterceptor {
    @Resource
    private AdminsService adminsService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(AuthConsts.LOGIN_TOKEN_KEY);
        if (!StringUtils.hasText(token)) {
            throw TokenForbiddenException.of("token.is.empty");
        }
        String lang = request.getHeader(AuthConsts.USER_LANG);

        // 设置语言
        Locale locale = Locale.US;
        if (Objects.equals(lang, Locale.CHINA.toLanguageTag())) {
            locale = Locale.CHINA;
        }
        LocaleContextHolder.setLocale(locale);

        adminsService.checkLogin(token);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LocaleContextHolder.resetLocaleContext();
        RequestContextUtils.clear();
    }
}
